<template>
  <div class="key-person-list">
    <div class="module-container">
      <div class="module-header">
        <icon name="list" class="header-icon"></icon>
        <span class="header-title">重点关注对象</span>
      </div>

      <!-- 板块切换按钮 -->
      <div class="category-tabs">
        <div
          v-for="(tab, index) in categoryTabs"
          :key="index"
          class="tab-item"
          :class="{ active: activeTabIndex === index }"
          @click="switchTab(index)"
        >
          <icon :name="tab.icon" class="tab-icon"></icon>
          <span class="tab-text">{{ tab.name }}</span>
        </div>
      </div>

      <div class="module-content">
        <dv-border-box-12 class="content-box">
          <!-- 综合问题板块 -->
          <div v-if="activeTabIndex === 0" class="tab-content">
            <div class="study-problem-container">
              <div class="study-title">
                <span>综合问题学生列表</span>
              </div>
              <div class="filter-container">
                <span class="filter-label">按预警等级筛选：</span>
                <div class="filter-options">
                  <div
                    class="filter-option"
                    :class="{ active: selectedComprehensiveWarningLevel === 0 }"
                    @click="filterComprehensiveByWarningLevel(0)"
                  >全部</div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedComprehensiveWarningLevel === 1 }"
                    @click="filterComprehensiveByWarningLevel(1)"
                  ><span class="warning-level-1">无风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedComprehensiveWarningLevel === 2 }"
                    @click="filterComprehensiveByWarningLevel(2)"
                  ><span class="warning-level-2">低风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedComprehensiveWarningLevel === 3 }"
                    @click="filterComprehensiveByWarningLevel(3)"
                  ><span class="warning-level-3">中风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedComprehensiveWarningLevel === 4 }"
                    @click="filterComprehensiveByWarningLevel(4)"
                  ><span class="warning-level-4">高风险</span></div>
                </div>
              </div>
              <div
                v-if="loading.comprehensive"
                class="loading-indicator"
              >
                <span>正在加载数据...</span>
              </div>
              <div v-else class="study-table-wrapper">
                <div
                  v-if="comprehensiveProblemStudents.length === 0"
                  class="no-data-message"
                >
                  <p>暂无数据或数据加载失败</p>
                  <button
                    @click="loadComprehensiveData"
                    class="reload-btn"
                  >
                    重新加载
                  </button>
                </div>
                <div v-else class="study-table-container">
                  <el-row style="height: 100%">
                    <el-table
                      :data="filteredComprehensiveProblemStudents"
                      style="width: 100%"
                      height="90%"
                    >
                      <el-table-column
                        type="index"
                        label="序号"
                        width="60"
                      ></el-table-column>
                      <el-table-column
                        prop="name"
                        label="姓名"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="group"
                        label="组别"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="className"
                        label="班级"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="score"
                        label="综合得分"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="warningLevel"
                        label="预警等级"
                        width="100"
                      >
                        <template slot-scope="scope">
                          <span :class="'warning-level-' + (scope.row.warningLevel === '高风险' ? '4' :
                                                          scope.row.warningLevel === '中风险' ? '3' :
                                                          scope.row.warningLevel === '低风险' ? '2' : '1')">
                            {{ scope.row.warningLevel }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="warningReason"
                        label="预警原因"
                      >
                        <template slot-scope="scope">
                          <span :class="getWarningReasonClass(scope.row.warningReason)">
                            {{ scope.row.warningReason }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="操作"
                        width="120"
                      >
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="primary"
                            @click="checkAndViewStudentDetail(scope.row)"
                          >查看详情</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="data-summary">
                      <p>
                        共找到
                        <span class="highlight">{{
                          comprehensiveHighRiskCount
                        }}</span>
                        名综合问题高风险学生
                      </p>
                    </div>
                  </el-row>
                </div>
              </div>
            </div>
          </div>

          <!-- 学习问题板块 -->
          <div v-if="activeTabIndex === 1" class="tab-content">
            <!-- 学习综合问题子板块 -->
            <div v-if="activeStudyTabIndex === 0" class="sub-tab-content">
              <div class="study-problem-container">
                <div class="study-title">
                  <div class="title-text-container">
                    <span>学习问题学生列表</span>
                    <div class="title-icon-container">
                      <i
                        class="el-icon-reading book-icon"
                        @mouseenter="showStudyTooltip = true"
                        @mouseleave="showStudyTooltip = false"
                      ></i>
                      <div
                        v-if="showStudyTooltip"
                        class="study-tooltip"
                      >
                        {{ studyInfoText }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="filter-container">
                  <span class="filter-label">按预警等级筛选：</span>
                  <div class="filter-options">
                    <div
                      class="filter-option"
                      :class="{ active: selectedStudyWarningLevel === 0 }"
                      @click="filterStudyByWarningLevel(0)"
                    >全部</div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedStudyWarningLevel === 1 }"
                      @click="filterStudyByWarningLevel(1)"
                    ><span class="warning-level-1">无风险</span></div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedStudyWarningLevel === 2 }"
                      @click="filterStudyByWarningLevel(2)"
                    ><span class="warning-level-2">低风险</span></div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedStudyWarningLevel === 3 }"
                      @click="filterStudyByWarningLevel(3)"
                    ><span class="warning-level-3">中风险</span></div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedStudyWarningLevel === 4 }"
                      @click="filterStudyByWarningLevel(4)"
                    ><span class="warning-level-4">高风险</span></div>
                  </div>
                </div>
                <div
                  v-if="loading.studyComprehensive"
                  class="loading-indicator"
                >
                  <span>正在加载数据...</span>
                </div>
                <div v-else class="study-table-wrapper">
                  <div
                    v-if="studyProblemStudents.length === 0"
                    class="no-data-message"
                  >
                    <p>暂无数据或数据加载失败</p>
                    <button
                      @click="loadStudyComprehensiveData"
                      class="reload-btn"
                    >
                      重新加载
                    </button>
                  </div>
                  <div v-else class="study-table-container">
                    <el-row style="height: 100%">
                      <el-table
                        :data="filteredStudyProblemStudents"
                        style="width: 100%"
                        height="90%"
                      >
                        <el-table-column
                          type="index"
                          label="序号"
                          width="60"
                        ></el-table-column>
                        <el-table-column
                          prop="name"
                          label="姓名"
                          width="100"
                        ></el-table-column>
                        <el-table-column
                          prop="group"
                          label="组别"
                          width="80"
                        ></el-table-column>
                        <el-table-column
                          prop="className"
                          label="班级"
                          width="80"
                        ></el-table-column>
                        <el-table-column
                          prop="score"
                          label="综合得分"
                          width="100"
                        ></el-table-column>
                        <el-table-column
                          prop="warningLevel"
                          label="预警等级"
                          width="100"
                        >
                          <template slot-scope="scope">
                            <span :class="'warning-level-' + (scope.row.warningLevel === '高风险' ? '4' :
                                                            scope.row.warningLevel === '中风险' ? '3' :
                                                            scope.row.warningLevel === '低风险' ? '2' : '1')">
                              {{ scope.row.warningLevel }}
                            </span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="warningReason"
                          label="预警原因"
                        >
                          <template slot-scope="scope">
                            <span :class="getWarningReasonClass(scope.row.warningReason)">
                              {{ scope.row.warningReason }}
                            </span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="操作"
                          width="120"
                        >
                          <template slot-scope="scope">
                            <el-button
                              size="mini"
                              type="primary"
                              @click="checkAndViewStudentDetail(scope.row)"
                            >查看详情</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                      <div class="data-summary">
                        <p>
                          共找到
                          <span class="highlight">{{
                            studyHighRiskCount
                          }}</span>
                          名学习问题高风险学生
                        </p>
                      </div>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 健康问题板块 -->
          <div v-if="activeTabIndex === 2" class="tab-content">
            <!-- 健康问题子板块 -->
            <div v-if="activeHealthTabIndex === 0" class="sub-tab-content">
              <div class="study-problem-container">
                <div class="study-title">
                  <div class="title-text-container">
                    <span>健康问题学生列表</span>
                    <div class="title-icon-container">
                      <i
                        class="el-icon-reading book-icon"
                        @mouseenter="showHealthTooltip = true"
                        @mouseleave="showHealthTooltip = false"
                      ></i>
                      <div
                        v-if="showHealthTooltip"
                        class="health-tooltip"
                      >
                        {{ healthInfoText }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="filter-container">
                  <span class="filter-label">按预警等级筛选：</span>
                  <div class="filter-options">
                    <div
                      class="filter-option"
                      :class="{ active: selectedHealthWarningLevel === 0 }"
                      @click="filterHealthByWarningLevel(0)"
                    >全部</div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedHealthWarningLevel === 1 }"
                      @click="filterHealthByWarningLevel(1)"
                    ><span class="warning-level-1">无风险</span></div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedHealthWarningLevel === 2 }"
                      @click="filterHealthByWarningLevel(2)"
                    ><span class="warning-level-2">低风险</span></div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedHealthWarningLevel === 3 }"
                      @click="filterHealthByWarningLevel(3)"
                    ><span class="warning-level-3">中风险</span></div>
                    <div
                      class="filter-option"
                      :class="{ active: selectedHealthWarningLevel === 4 }"
                      @click="filterHealthByWarningLevel(4)"
                    ><span class="warning-level-4">高风险</span></div>
                  </div>
                </div>
                <div
                  v-if="loading.healthComprehensive"
                  class="loading-indicator"
                >
                  <span>正在加载数据...</span>
                </div>
                <div v-else class="study-table-wrapper">
                  <div
                    v-if="healthProblemStudents.length === 0"
                    class="no-data-message"
                  >
                    <p>暂无数据或数据加载失败</p>
                    <button
                      @click="loadHealthComprehensiveData"
                      class="reload-btn"
                    >
                      重新加载
                    </button>
                  </div>
                  <div v-else class="study-table-container">
                    <el-row style="height: 100%">
                      <el-table
                        :data="filteredHealthProblemStudents"
                        style="width: 100%"
                        height="90%"
                      >
                        <el-table-column
                          type="index"
                          label="序号"
                          width="60"
                        ></el-table-column>
                        <el-table-column
                          prop="name"
                          label="姓名"
                          width="100"
                        ></el-table-column>
                        <el-table-column
                          prop="group"
                          label="组别"
                          width="80"
                        ></el-table-column>
                        <el-table-column
                          prop="className"
                          label="班级"
                          width="80"
                        ></el-table-column>
                        <el-table-column
                          prop="score"
                          label="综合得分"
                          width="100"
                        ></el-table-column>
                        <el-table-column
                          prop="warningLevel"
                          label="预警等级"
                          width="100"
                        >
                          <template slot-scope="scope">
                            <span :class="'warning-level-' + (scope.row.warningLevel === '高风险' ? '4' :
                                                            scope.row.warningLevel === '中风险' ? '3' :
                                                            scope.row.warningLevel === '低风险' ? '2' : '1')">
                              {{ scope.row.warningLevel }}
                            </span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="warningReason"
                          label="预警原因"
                        >
                          <template slot-scope="scope">
                            <span :class="getWarningReasonClass(scope.row.warningReason)">
                              {{ scope.row.warningReason }}
                            </span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          label="操作"
                          width="120"
                        >
                          <template slot-scope="scope">
                            <el-button
                              size="mini"
                              type="primary"
                              @click="checkAndViewStudentDetail(scope.row)"
                            >查看详情</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                      <div class="data-summary">
                        <p>
                          共找到
                          <span class="highlight">{{
                            healthHighRiskCount
                          }}</span>
                          名健康问题高风险学生
                        </p>
                      </div>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 生活问题板块 -->
          <div v-if="activeTabIndex === 3" class="tab-content">
            <div class="study-problem-container">
              <div class="study-title">
                <span>生活问题学生列表</span>
              </div>
              <div class="filter-container">
                <span class="filter-label">按预警等级筛选：</span>
                <div class="filter-options">
                  <div
                    class="filter-option"
                    :class="{ active: selectedLifeWarningLevel === 0 }"
                    @click="filterLifeByWarningLevel(0)"
                  >全部</div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedLifeWarningLevel === 1 }"
                    @click="filterLifeByWarningLevel(1)"
                  ><span class="warning-level-1">无风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedLifeWarningLevel === 2 }"
                    @click="filterLifeByWarningLevel(2)"
                  ><span class="warning-level-2">低风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedLifeWarningLevel === 3 }"
                    @click="filterLifeByWarningLevel(3)"
                  ><span class="warning-level-3">中风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedLifeWarningLevel === 4 }"
                    @click="filterLifeByWarningLevel(4)"
                  ><span class="warning-level-4">高风险</span></div>
                </div>
              </div>
              <div v-if="loading.life" class="loading-indicator">
                <span>正在加载数据...</span>
              </div>
              <div v-else class="study-table-wrapper">
                <div v-if="lifeProblemStudents.length === 0" class="no-data-message">
                  <p>暂无数据或数据加载失败</p>
                  <button @click="loadLifeData" class="reload-btn">
                    重新加载
                  </button>
                </div>
                <div v-else class="study-table-container">
                  <el-row style="height: 100%">
                    <el-table
                      :data="filteredLifeProblemStudents"
                      style="width: 100%"
                      height="90%"
                    >
                      <el-table-column
                        type="index"
                        label="序号"
                        width="60"
                      ></el-table-column>
                      <el-table-column
                        prop="name"
                        label="姓名"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="group"
                        label="组别"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="className"
                        label="班级"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="score"
                        label="综合得分"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="warningLevel"
                        label="预警等级"
                        width="100"
                      >
                        <template slot-scope="scope">
                          <span :class="'warning-level-' + (scope.row.warningLevel === '高风险' ? '4' :
                                                          scope.row.warningLevel === '中风险' ? '3' :
                                                          scope.row.warningLevel === '低风险' ? '2' : '1')">
                            {{ scope.row.warningLevel }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="warningReason"
                        label="预警原因"
                      >
                        <template slot-scope="scope">
                          <span :class="getWarningReasonClass(scope.row.warningReason)">
                            {{ scope.row.warningReason }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="操作"
                        width="120"
                      >
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="primary"
                            @click="checkAndViewStudentDetail(scope.row)"
                          >查看详情</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="data-summary">
                      <p>
                        共找到
                        <span class="highlight">{{
                          lifeHighRiskCount
                        }}</span>
                        名生活问题高风险学生
                      </p>
                    </div>
                  </el-row>
                </div>
              </div>
            </div>
          </div>

          <!-- 作风养成问题板块 -->
          <div v-if="activeTabIndex === 4" class="tab-content">
            <div class="study-problem-container">
              <div class="study-title">
                <div class="title-text-container">
                  <span>作风养成问题学生列表</span>
                  <div class="title-icon-container">
                    <i
                      class="el-icon-reading book-icon"
                      @mouseenter="showMentalTooltip = true"
                      @mouseleave="showMentalTooltip = false"
                    ></i>
                    <div
                      v-if="showMentalTooltip"
                      class="mental-tooltip"
                    >
                      {{ mentalInfoText }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="filter-container">
                <span class="filter-label">按预警等级筛选：</span>
                <div class="filter-options">
                  <div
                    class="filter-option"
                    :class="{ active: selectedMentalWarningLevel === 0 }"
                    @click="filterMentalByWarningLevel(0)"
                  >全部</div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedMentalWarningLevel === 1 }"
                    @click="filterMentalByWarningLevel(1)"
                  ><span class="warning-level-1">无风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedMentalWarningLevel === 2 }"
                    @click="filterMentalByWarningLevel(2)"
                  ><span class="warning-level-2">低风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedMentalWarningLevel === 3 }"
                    @click="filterMentalByWarningLevel(3)"
                  ><span class="warning-level-3">中风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedMentalWarningLevel === 4 }"
                    @click="filterMentalByWarningLevel(4)"
                  ><span class="warning-level-4">高风险</span></div>
                </div>
              </div>
              <div v-if="loading.mental" class="loading-indicator">
                <span>正在加载数据...</span>
              </div>
              <div v-else class="study-table-wrapper">
                <div v-if="mentalProblemStudents.length === 0" class="no-data-message">
                  <p>暂无数据或数据加载失败</p>
                  <button @click="loadMentalData" class="reload-btn">
                    重新加载
                  </button>
                </div>
                <div v-else class="study-table-container">
                  <el-row style="height: 100%">
                    <el-table
                      :data="filteredMentalProblemStudents"
                      style="width: 100%"
                      height="90%"
                    >
                      <el-table-column
                        type="index"
                        label="序号"
                        width="60"
                      ></el-table-column>
                      <el-table-column
                        prop="name"
                        label="姓名"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="group"
                        label="组别"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="className"
                        label="班级"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="score"
                        label="综合得分"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="warningLevel"
                        label="预警等级"
                        width="100"
                      >
                        <template slot-scope="scope">
                          <span :class="'warning-level-' + (scope.row.warningLevel === '高风险' ? '4' :
                                                          scope.row.warningLevel === '中风险' ? '3' :
                                                          scope.row.warningLevel === '低风险' ? '2' : '1')">
                            {{ scope.row.warningLevel }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="warningReason"
                        label="预警原因"
                      >
                        <template slot-scope="scope">
                          <span :class="getWarningReasonClass(scope.row.warningReason)">
                            {{ scope.row.warningReason }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="操作"
                        width="120"
                      >
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="primary"
                            @click="checkAndViewStudentDetail(scope.row)"
                          >查看详情</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="data-summary">
                      <p>
                        共找到
                        <span class="highlight">{{
                          mentalHighRiskCount
                        }}</span>
                        名思想问题高风险学生
                      </p>
                    </div>
                  </el-row>
                </div>
              </div>
            </div>
          </div>

          <!-- 社交问题板块 -->
          <div v-if="activeTabIndex === 5" class="tab-content">
            <div class="study-problem-container">
              <div class="study-title">
                <span>社交问题学生列表</span>
              </div>
              <div class="filter-container">
                <span class="filter-label">按预警等级筛选：</span>
                <div class="filter-options">
                  <div
                    class="filter-option"
                    :class="{ active: selectedSocialWarningLevel === 0 }"
                    @click="filterSocialByWarningLevel(0)"
                  >全部</div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedSocialWarningLevel === 1 }"
                    @click="filterSocialByWarningLevel(1)"
                  ><span class="warning-level-1">无风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedSocialWarningLevel === 2 }"
                    @click="filterSocialByWarningLevel(2)"
                  ><span class="warning-level-2">低风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedSocialWarningLevel === 3 }"
                    @click="filterSocialByWarningLevel(3)"
                  ><span class="warning-level-3">中风险</span></div>
                  <div
                    class="filter-option"
                    :class="{ active: selectedSocialWarningLevel === 4 }"
                    @click="filterSocialByWarningLevel(4)"
                  ><span class="warning-level-4">高风险</span></div>
                </div>
              </div>
              <div v-if="loading.social" class="loading-indicator">
                <span>正在加载数据...</span>
              </div>
              <div v-else class="study-table-wrapper">
                <div v-if="socialProblemStudents.length === 0" class="no-data-message">
                  <p>暂无数据或数据加载失败</p>
                  <button @click="loadSocialData" class="reload-btn">
                    重新加载
                  </button>
                </div>
                <div v-else class="study-table-container">
                  <el-row style="height: 100%">
                    <el-table
                      :data="filteredSocialProblemStudents"
                      style="width: 100%"
                      height="90%"
                    >
                      <el-table-column
                        type="index"
                        label="序号"
                        width="60"
                      ></el-table-column>
                      <el-table-column
                        prop="name"
                        label="姓名"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="group"
                        label="组别"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="className"
                        label="班级"
                        width="80"
                      ></el-table-column>
                      <el-table-column
                        prop="score"
                        label="综合得分"
                        width="100"
                      ></el-table-column>
                      <el-table-column
                        prop="warningLevel"
                        label="预警等级"
                        width="100"
                      >
                        <template slot-scope="scope">
                          <span :class="'warning-level-' + (scope.row.warningLevel === '高风险' ? '4' :
                                                          scope.row.warningLevel === '中风险' ? '3' :
                                                          scope.row.warningLevel === '低风险' ? '2' : '1')">
                            {{ scope.row.warningLevel }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="warningReason"
                        label="预警原因"
                      >
                        <template slot-scope="scope">
                          <span :class="getWarningReasonClass(scope.row.warningReason)">
                            {{ scope.row.warningReason }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="操作"
                        width="120"
                      >
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="primary"
                            @click="checkAndViewStudentDetail(scope.row)"
                          >查看详情</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="data-summary">
                      <p>
                        共找到
                        <span class="highlight">{{
                          socialHighRiskCount
                        }}</span>
                        名社交问题高风险学生
                      </p>
                    </div>
                  </el-row>
                </div>
              </div>
            </div>
          </div>
        </dv-border-box-12>
      </div>
    </div>
  </div>
</template>

<script>
import keypersonApi from '@/api/keyperson';

export default {
  name: "KeyPersonList",
  data() {
    return {
      activeTabIndex: 0,
      activeHealthTabIndex: 0,
      activeStudyTabIndex: 0, // 默认显示学习综合问题
      categoryTabs: [
        { name: "综合问题", icon: "chart-pie" },
        { name: "学习问题", icon: "graduation-cap" },
        { name: "健康问题", icon: "heartbeat" },
        { name: "生活问题", icon: "home" },
        { name: "作风养成问题", icon: "brain" },
        { name: "社交问题", icon: "users" },
      ],
      studySubTabs: [
        { name: "学习综合问题", icon: "" },
      ],
      healthSubTabs: [
        { name: "健康问题", icon: "heartbeat" },
      ],
      medicalRecords: [],
      sportRecords: [],
      studyComprehensiveRecords: [], // 学习综合数据
      healthComprehensiveRecords: [], // 健康综合数据
      loading: {
        medical: false,
        sport: false,
        study: false,
        studyComprehensive: false,
        healthComprehensive: false,
        life: false,
        mental: false,
        social: false,
        comprehensive: false,
      },
      studyRecords: [],
      studyProblemStudents: [], // 学习问题学生
      filteredStudyProblemStudents: [], // 筛选后的学习问题学生
      selectedStudyWarningLevel: 0, // 选中的学习预警等级，0表示全部
      healthProblemStudents: [], // 健康问题学生
      filteredHealthProblemStudents: [], // 筛选后的健康问题学生
      selectedHealthWarningLevel: 0, // 选中的健康预警等级，0表示全部
      lifeRecords: [], // 生活数据
      lifeProblemStudents: [], // 生活问题学生
      filteredLifeProblemStudents: [], // 筛选后的生活问题学生
      selectedLifeWarningLevel: 0, // 选中的生活预警等级，0表示全部
      mentalRecords: [], // 思想数据
      mentalProblemStudents: [], // 思想问题学生
      filteredMentalProblemStudents: [], // 筛选后的思想问题学生
      selectedMentalWarningLevel: 0, // 选中的思想预警等级，0表示全部
      socialRecords: [], // 社交数据
      socialProblemStudents: [], // 社交问题学生
      filteredSocialProblemStudents: [], // 筛选后的社交问题学生
      selectedSocialWarningLevel: 0, // 选中的社交预警等级，0表示全部
      selectedComprehensiveWarningLevel: 0, // 选中的综合预警等级，0表示全部
      comprehensiveProblemStudents: [], // 综合问题学生
      filteredComprehensiveProblemStudents: [], // 筛选后的综合问题学生
      mentalInfoText: '', // 思想问题说明文本
      showMentalTooltip: false, // 控制思想问题提示框显示
      studyInfoText: '', // 学习问题说明文本
      showStudyTooltip: false, // 控制学习问题提示框显示
      healthInfoText: '', // 健康问题说明文本
      showHealthTooltip: false, // 控制健康问题提示框显示
    };
  },
  computed: {
    // 计算本月就医次数过多的人员
    medicalFrequentVisitors() {
      if (!this.medicalRecords.length) return [];

      // 获取当前月份
      const currentDate = new Date();
      const currentMonth = currentDate.getMonth() + 1; // 月份从0开始

      // 按姓名分组统计就医次数
      const visitorsMap = new Map();

      this.medicalRecords.forEach((record) => {
        // 解析日期中的月份
        let recordMonth;
        if (record.日期) {
          const dateMatch = record.日期.match(/(\d+)月/);
          if (dateMatch) {
            recordMonth = parseInt(dateMatch[1]);
          }
        }

        // 只统计当前月的记录
        if (recordMonth === currentMonth) {
          const name = record.姓名;
          if (!visitorsMap.has(name)) {
            visitorsMap.set(name, {
              name: name,
              className: record.班级,
              major: record.专业,
              visitCount: 1,
              dates: [record.日期],
              reasons: [record.病因],
              hospitalStatus: [record.是否住院],
            });
          } else {
            const visitor = visitorsMap.get(name);
            visitor.visitCount++;
            visitor.dates.push(record.日期);
            visitor.reasons.push(record.病因);
            visitor.hospitalStatus.push(record.是否住院);
          }
        }
      });

      // 过滤出就医次数大于等于2次的人员
      const frequentVisitors = Array.from(visitorsMap.values())
        .filter((visitor) => visitor.visitCount >= 2)
        .sort((a, b) => b.visitCount - a.visitCount); // 按就医次数降序排序

      return frequentVisitors;
    },

    // 计算体能测试两项均不及格的学生
    sportFailedStudents() {
      if (!this.sportRecords.length) return [];

      console.log("Sport records loaded:", this.sportRecords.length);

      // 过滤出两项均不及格的学生
      const failedStudents = this.sportRecords.filter((student) => {
        // 检查引体向上和3000米是否都不及格
        const pullUpFailed = student["引体是否及格"] === "否";
        const runFailed = student["三千米是否及格"] === "否";

        // 确保两项都不是未参加
        const notMissing =
          student["三千米是否及格"] !== "未参加" &&
          student["引体是否及格"] !== "未参加";

        return pullUpFailed && runFailed && notMissing;
      });

      return failedStudents.map((student) => {
        return {
          name: student["姓名"],
          gender: student["性别"],
          className: student["班级"],
          pullUp: student["引体向上"],
          pullUpPass: student["引体是否及格"] === "是",
          run: student["三千米"],
          runPass: student["三千米是否及格"] === "是",
        };
      });
    },

    // 计算最近一次考试排名后10%的学生
    lowRankingStudents() {
      if (!this.studyRecords.length) return [];

      // 获取最近一次考试的考试节点
      const examPoints = [
        ...new Set(this.studyRecords.map((record) => record.考试节点名称)),
      ];
      const latestExamPoint = examPoints.sort().pop(); // 假设按字母顺序排序后最后一个是最新的

      if (!latestExamPoint) return [];

      console.log("最近一次考试节点:", latestExamPoint);

      // 获取最近一次考试的所有记录
      const latestExamRecords = this.studyRecords.filter(
        (record) => record.考试节点名称 === latestExamPoint
      );

      // 按科目和专业分组
      const subjectMajorGroups = {};

      latestExamRecords.forEach((record) => {
        const key = `${record.科目}-${record.专业}`;
        if (!subjectMajorGroups[key]) {
          subjectMajorGroups[key] = [];
        }
        subjectMajorGroups[key].push(record);
      });

      // 对每个科目-专业组合，找出排名后10%的学生
      let lowRankingResults = [];

      Object.values(subjectMajorGroups).forEach((group) => {
        if (group.length === 0) return;

        // 按排名从大到小排序（排名数字越大表示排名越靠后）
        group.sort((a, b) => parseInt(b.排名) - parseInt(a.排名));

        // 取排名后10%的学生
        const cutoffIndex = Math.max(1, Math.ceil(group.length * 0.1));
        const lowRankingStudents = group.slice(0, cutoffIndex);

        lowRankingResults = [...lowRankingResults, ...lowRankingStudents];
      });

      // 按排名从大到小排序
      lowRankingResults.sort((a, b) => parseInt(b.排名) - parseInt(a.排名));

      return lowRankingResults;
    },

    // 计算各模块高风险人员数量
    comprehensiveHighRiskCount() {
      return this.comprehensiveProblemStudents.filter(student =>
        student.warningLevel === '高风险'
      ).length;
    },

    studyHighRiskCount() {
      return this.studyProblemStudents.filter(student =>
        student.warningLevel === '高风险'
      ).length;
    },

    healthHighRiskCount() {
      return this.healthProblemStudents.filter(student =>
        student.warningLevel === '高风险'
      ).length;
    },

    lifeHighRiskCount() {
      return this.lifeProblemStudents.filter(student =>
        student.warningLevel === '高风险'
      ).length;
    },

    mentalHighRiskCount() {
      return this.mentalProblemStudents.filter(student =>
        student.warningLevel === '高风险'
      ).length;
    },

    socialHighRiskCount() {
      return this.socialProblemStudents.filter(student =>
        student.warningLevel === '高风险'
      ).length;
    },
  },
  mounted() {
    // 进入页面时自动触发当前tab的加载方法
    this.autoReload();
    // 加载思想问题说明文本
    this.loadMentalInfoText();
    // 加载学习问题说明文本
    this.loadStudyInfoText();
    // 加载健康问题说明文本
    this.loadHealthInfoText();
  },
  methods: {
    autoReload() {
      // 根据当前tab自动调用对应加载方法
      switch (this.activeTabIndex) {
        case 0:
          this.loadComprehensiveData();
          break;
        case 1:
          this.loadStudyComprehensiveData();
          break;
        case 2:
          this.loadHealthComprehensiveData();
          break;
        case 3:
          this.loadLifeData();
          break;
        case 4:
          this.loadMentalData();
          break;
        case 5:
          this.loadSocialData();
          break;
      }
    },
    switchTab(index) {
      this.activeTabIndex = index;

      // 根据选择的标签加载相关数据
      if (index === 0) {
        // 综合问题板块
        this.loadComprehensiveData();
      } else if (index === 1) {
        // 学习问题板块
        this.loadStudyComprehensiveData();
      } else if (index === 2) {
        // 健康问题板块
        this.loadHealthComprehensiveData();
      } else if (index === 3) {
        // 生活问题板块
        this.loadLifeData();
      } else if (index === 4) {
        // 思想问题板块
        this.loadMentalData();
      } else if (index === 5) {
        // 社交问题板块
        this.loadSocialData();
      }
    },

    // 切换学习问题子模块
    switchStudyTab(index) {
      this.activeStudyTabIndex = index;

      // 加载学习问题数据
      this.loadStudyComprehensiveData();
    },

    // 切换健康问题子模块
    switchHealthTab(index) {
      this.activeHealthTabIndex = index;

      // 加载健康问题数据
      this.loadHealthComprehensiveData();
    },

    // 加载988就医数据
    async loadMedicalData() {
      if (this.medicalRecords.length > 0) return; // 如果已经加载过数据，则不重复加载

      this.loading.medical = true;
      try {
        const response = await fetch("/data/gerendangan/jiankang/988.csv");
        const csvText = await response.text();
        this.medicalRecords = this.parseCSV(csvText);
      } catch (error) {
        console.error("加载988就医数据失败:", error);
      } finally {
        this.loading.medical = false;
      }
    },

    // 加载体能测试数据
    async loadSportData() {
      // 强制重新加载数据进行调试
      this.sportRecords = [];

      this.loading.sport = true;
      try {
        const response = await fetch("/data/sport.csv");
        const csvText = await response.text();
        this.sportRecords = this.parseCSV(csvText);

        // 调试信息
        console.log(
          "加载体能测试数据成功，总记录数:",
          this.sportRecords.length
        );
        if (this.sportRecords.length > 0) {
          console.log("第一条记录示例:", this.sportRecords[0]);

          // 检查两项均不及格的学生
          const bothFailed = this.sportRecords.filter(
            (student) =>
              student["引体是否及格"] === "否" &&
              student["三千米是否及格"] === "否"
          );
          console.log("两项均不及格的学生数:", bothFailed.length);
          if (bothFailed.length > 0) {
            console.log("两项均不及格学生示例:", bothFailed[0]);
          }
        }
      } catch (error) {
        console.error("加载体能测试数据失败:", error);
      } finally {
        this.loading.sport = false;
      }
    },

    // 解析CSV文件
    parseCSV(csvText) {
      // 分行处理
      const lines = csvText.split("\n");
      if (lines.length <= 1) return [];

      // 获取头部列名
      const headers = lines[0].split(",");

      // 处理数据行
      const records = [];
      for (let i = 1; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) continue; // 跳过空行

        const values = line.split(",");
        if (values.length < headers.length) continue; // 跳过不完整的行

        const record = {};
        headers.forEach((header, index) => {
          // 确保列名作为字典键
          const headerKey = header.trim();
          record[headerKey] = values[index] ? values[index].trim() : "";
        });

        records.push(record);
      }

      return records;
    },

    // 加载学习成绩数据
    async loadStudyData() {
      if (this.studyRecords.length > 0) return; // 如果已经加载过数据，则不重复加载

      this.loading.study = true;
      try {
        const response = await fetch(
          "/data/gerendangan/study/xuekechengji.csv"
        );
        const csvText = await response.text();
        this.studyRecords = this.parseCSV(csvText);
        console.log(
          "学习成绩数据加载完成，共",
          this.studyRecords.length,
          "条记录"
        );
      } catch (error) {
        console.error("加载学习成绩数据失败:", error);
      } finally {
        this.loading.study = false;
      }
    },

    // 查看学生详情
    viewStudentDetail(student) {
      // 查找学生的虚拟学号
      // 由于xuekechengji.csv中没有虚拟学号，我们需要构造一个
      // 这里使用姓名+班级+组别作为唯一标识
      const studentId = `${student.姓名}_${student.班级}_${
        student.组别 || "0"
      }`;

      // 跳转到学生详情页面
      this.$router.push({
        name: "student-detail",
        params: { id: studentId },
      });
    },

    // 检查学生是否存在于个人档案，并查看详情
    async checkAndViewStudentDetail(row) {
      try {
        const res = await keypersonApi.getStuByNameClass({
          name: row.name,
          classes: row.className
        });
        if (res && res.code === '200' && res.data && res.data.studentId) {
          this.$router.push({
            name: 'student-detail',
            params: { id: res.data.studentId }
          });
        } else {
          this.$message({
            message: `未找到学生"${row.name}"的个人档案信息`,
            type: 'warning'
          });
        }
      } catch (error) {
        this.$message({
          message: `查询学生"${row.name}"的个人档案信息失败`,
          type: 'error'
        });
      }
    },

    // 加载学习综合数据
    async loadStudyComprehensiveData() {
      this.loading.studyComprehensive = true;
      try {
        const res = await keypersonApi.getKeyPersonByModel('study');
        if (res && res.code === '200' && Array.isArray(res.data)) {
          this.studyProblemStudents = res.data.map(item => ({
            name: item.name || '',
            group: item.groupName || '',
            className: item.classes || '',
            score: item.studyScore || item.score || '',
            warningLevel: item.warningLevel || '未知',
            warningReason: item.keyReason || ''
          })).sort((a, b) => Number(a.score) - Number(b.score));
          this.filteredStudyProblemStudents = [...this.studyProblemStudents];
          console.log('加载的学习问题学生数据:', this.studyProblemStudents);
        } else {
          this.studyProblemStudents = [];
          this.filteredStudyProblemStudents = [];
        }
      } catch (error) {
        this.studyProblemStudents = [];
        this.filteredStudyProblemStudents = [];
        console.error('加载学习问题数据失败:', error);
      } finally {
        this.loading.studyComprehensive = false;
      }
    },

    // 按预警等级筛选学习问题学生
    filterStudyByWarningLevel(level) {
      this.selectedStudyWarningLevel = level;
      if (level === 0) {
        this.filteredStudyProblemStudents = [...this.studyProblemStudents];
      } else {
        const levelMap = {
          1: '无风险',
          2: '低风险',
          3: '中风险',
          4: '高风险'
        };
        this.filteredStudyProblemStudents = this.studyProblemStudents.filter(
          student => student.warningLevel === levelMap[level]
        );
      }
      console.log('筛选后的学习问题学生数量:', this.filteredStudyProblemStudents.length);
    },

    // 加载健康问题数据
    async loadHealthComprehensiveData() {
      this.loading.healthComprehensive = true;
      try {
        const res = await keypersonApi.getKeyPersonByModel('health');
        if (res && res.code === '200' && Array.isArray(res.data)) {
          this.healthProblemStudents = res.data.map(item => ({
            name: item.name || '',
            group: item.groupName || '',
            className: item.classes || '',
            score: item.healthScore || item.score || '',
            warningLevel: item.warningLevel || '未知',
            warningReason: item.keyReason || ''
          })).sort((a, b) => Number(a.score) - Number(b.score));
          this.filteredHealthProblemStudents = [...this.healthProblemStudents];
          console.log('加载的健康问题学生数据:', this.healthProblemStudents);
        } else {
          this.healthProblemStudents = [];
          this.filteredHealthProblemStudents = [];
        }
      } catch (error) {
        this.healthProblemStudents = [];
        this.filteredHealthProblemStudents = [];
        console.error('加载健康问题数据失败:', error);
      } finally {
        this.loading.healthComprehensive = false;
      }
    },

    // 按预警等级筛选健康问题学生
    filterHealthByWarningLevel(level) {
      this.selectedHealthWarningLevel = level;
      if (level === 0) {
        this.filteredHealthProblemStudents = [...this.healthProblemStudents];
      } else {
        const levelMap = {
          1: '无风险',
          2: '低风险',
          3: '中风险',
          4: '高风险'
        };
        this.filteredHealthProblemStudents = this.healthProblemStudents.filter(
          student => student.warningLevel === levelMap[level]
        );
      }
      console.log('筛选后的健康问题学生数量:', this.filteredHealthProblemStudents.length);
    },

    // 通过姓名查看学生详情
    viewStudentDetailByName(name) {
      // 构造一个简单的ID，使用姓名作为唯一标识
      const studentId = `${name}_default_0`;

      // 跳转到学生详情页面
      this.$router.push({
        name: "student-detail",
        params: { id: studentId },
      });
    },

    // 加载生活问题数据
    async loadLifeData() {
      this.loading.life = true;
      try {
        const res = await keypersonApi.getKeyPersonByModel('life');
        if (res && res.code === '200' && Array.isArray(res.data)) {
          this.lifeProblemStudents = res.data.map(item => ({
            name: item.name || '',
            group: item.groupName || '',
            className: item.classes || '',
            score: item.lifeScore || item.score || '',
            warningLevel: item.warningLevel || '未知',
            warningReason: item.keyReason || ''
          })).sort((a, b) => Number(a.score) - Number(b.score));
          this.filteredLifeProblemStudents = [...this.lifeProblemStudents];
          console.log('加载的生活问题学生数据:', this.lifeProblemStudents);
        } else {
          this.lifeProblemStudents = [];
          this.filteredLifeProblemStudents = [];
        }
      } catch (error) {
        this.lifeProblemStudents = [];
        this.filteredLifeProblemStudents = [];
        console.error('加载生活问题数据失败:', error);
      } finally {
        this.loading.life = false;
      }
    },

    // 按预警等级筛选生活问题学生
    filterLifeByWarningLevel(level) {
      this.selectedLifeWarningLevel = level;
      if (level === 0) {
        this.filteredLifeProblemStudents = [...this.lifeProblemStudents];
      } else {
        const levelMap = {
          1: '无风险',
          2: '低风险',
          3: '中风险',
          4: '高风险'
        };
        this.filteredLifeProblemStudents = this.lifeProblemStudents.filter(
          student => student.warningLevel === levelMap[level]
        );
      }
      console.log('筛选后的生活问题学生数量:', this.filteredLifeProblemStudents.length);
    },

    // 加载作风养成问题数据
    async loadMentalData() {
      this.loading.mental = true;
      try {
        const res = await keypersonApi.getKeyPersonByModel('thought');
        if (res && res.code === '200' && Array.isArray(res.data)) {
          this.mentalProblemStudents = res.data.map(item => ({
            name: item.name || '',
            group: item.groupName || '',
            className: item.classes || '',
            score: item.thoughtScore || item.score || '',
            warningLevel: item.warningLevel || '未知',
            warningReason: item.keyReason || ''
          })).sort((a, b) => Number(a.score) - Number(b.score));
          this.filteredMentalProblemStudents = [...this.mentalProblemStudents];
          console.log('加载的作风养成问题学生数据:', this.mentalProblemStudents);
        } else {
          this.mentalProblemStudents = [];
          this.filteredMentalProblemStudents = [];
        }
      } catch (error) {
        this.mentalProblemStudents = [];
        this.filteredMentalProblemStudents = [];
        console.error('加载思想问题数据失败:', error);
      } finally {
        this.loading.mental = false;
      }
    },

    // 按预警等级筛选思想问题学生
    filterMentalByWarningLevel(level) {
      this.selectedMentalWarningLevel = level;
      if (level === 0) {
        this.filteredMentalProblemStudents = [...this.mentalProblemStudents];
      } else {
        const levelMap = {
          1: '无风险',
          2: '低风险',
          3: '中风险',
          4: '高风险'
        };
        this.filteredMentalProblemStudents = this.mentalProblemStudents.filter(
          student => student.warningLevel === levelMap[level]
        );
      }
      console.log('筛选后的思想问题学生数量:', this.filteredMentalProblemStudents.length);
    },

    // 加载社交问题数据
    async loadSocialData() {
      this.loading.social = true;
      try {
        const res = await keypersonApi.getKeyPersonByModel('social');
        if (res && res.code === '200' && Array.isArray(res.data)) {
          this.socialProblemStudents = res.data.map(item => ({
            name: item.name || '',
            group: item.groupName || '',
            className: item.classes || '',
            score: item.socialScore || item.score || '',
            warningLevel: item.warningLevel ? parseInt(item.warningLevel) : 0,
            warningReason: item.keyReason || ''
          })).sort((a, b) => Number(a.score) - Number(b.score));
          this.filteredSocialProblemStudents = [...this.socialProblemStudents];
          console.log('加载的社交问题学生数据:', this.socialProblemStudents);
        } else {
          this.socialProblemStudents = [];
          this.filteredSocialProblemStudents = [];
        }
      } catch (error) {
        this.socialProblemStudents = [];
        this.filteredSocialProblemStudents = [];
        console.error('加载社交问题数据失败:', error);
      } finally {
        this.loading.social = false;
      }
    },

    // 按预警等级筛选社交问题学生
    filterSocialByWarningLevel(level) {
      this.selectedSocialWarningLevel = level;
      if (level === 0) {
        this.filteredSocialProblemStudents = [...this.socialProblemStudents];
      } else {
        const levelMap = {
          1: '无风险',
          2: '低风险',
          3: '中风险',
          4: '高风险'
        };
        this.filteredSocialProblemStudents = this.socialProblemStudents.filter(
          student => student.warningLevel === levelMap[level]
        );
      }
      console.log('筛选后的社交问题学生数量:', this.filteredSocialProblemStudents.length);
    },

    // 加载综合问题数据
    async loadComprehensiveData() {
      this.loading.comprehensive = true;
      try {
        const res = await keypersonApi.getKeyPersonByModel();
        if (res && res.code === '200' && Array.isArray(res.data)) {
          this.comprehensiveProblemStudents = res.data.map(item => ({
            name: item.name || '',
            group: item.groupName || '',
            className: item.classes || '',
            score: item.score || '',
            warningLevel: item.warningLevel || '未知',
            warningReason: item.keyReason || ''
          })).sort((a, b) => Number(a.score) - Number(b.score));
          this.filteredComprehensiveProblemStudents = [...this.comprehensiveProblemStudents];
          console.log('加载的综合问题学生数据:', this.comprehensiveProblemStudents);
        } else {
          this.comprehensiveProblemStudents = [];
          this.filteredComprehensiveProblemStudents = [];
        }
      } catch (error) {
        this.comprehensiveProblemStudents = [];
        this.filteredComprehensiveProblemStudents = [];
        console.error('加载综合问题数据失败:', error);
      } finally {
        this.loading.comprehensive = false;
      }
    },

    // 按预警等级筛选综合问题学生
    filterComprehensiveByWarningLevel(level) {
      this.selectedComprehensiveWarningLevel = level;
      if (level === 0) {
        this.filteredComprehensiveProblemStudents = [...this.comprehensiveProblemStudents];
      } else {
        const levelMap = {
          1: '无风险',
          2: '低风险',
          3: '中风险',
          4: '高风险'
        };
        this.filteredComprehensiveProblemStudents = this.comprehensiveProblemStudents.filter(
          student => student.warningLevel === levelMap[level]
        );
      }
      console.log('筛选后的学生数量:', this.filteredComprehensiveProblemStudents.length);
    },

    // 加载思想问题说明文本
    async loadMentalInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"5、"后面的文本，直到下一个序号或文件结束
          const regex = /5、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.mentalInfoText = match[1].trim();
            console.log('思想问题说明文本:', this.mentalInfoText);
          } else {
            console.error('未找到思想问题说明文本');
            this.mentalInfoText = '第二百一十三条  军队单位应当重视心理健康服务，组织经常性心理健康教育，做好心理评估、心理咨询和心理训练等工作；发现精神心理障碍或者疑似人员，应当及时送诊就医。';
          }
        } else {
          console.error('加载思想问题说明文本失败');
          this.mentalInfoText = '第二百一十三条  军队单位应当重视心理健康服务，组织经常性心理健康教育，做好心理评估、心理咨询和心理训练等工作；发现精神心理障碍或者疑似人员，应当及时送诊就医。';
        }
      } catch (error) {
        console.error('加载作风养成问题说明文本出错:', error);
        this.mentalInfoText = '第二百一十三条  军队单位应当重视心理健康服务，组织经常性心理健康教育，做好心理评估、心理咨询和心理训练等工作；发现精神心理障碍或者疑似人员，应当及时送诊就医。';
      }
    },

    // 加载学习问题说明文本
    async loadStudyInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"2、"后面的文本，直到下一个序号或文件结束
          const regex = /2、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.studyInfoText = match[1].trim();
            console.log('学习问题说明文本:', this.studyInfoText);
          } else {
            console.error('未找到学习问题说明文本');
            this.studyInfoText = '第四十八条 军队院校实行学员综合素质考核和全程筛选制度。院校应当对学员的思想政治、科学文化、军事专业、领导管理和身体心理等方面的综合素质进行定期考核，不合格的按照有关规定处理。第四十九条 学员在规定的修业年限内，学完教学计划规定的全部课程或者修满相应的学分，经考核合格的，准予毕业;未达到毕业条件的，作结业或者肄业处理。';
          }
        } else {
          console.error('加载学习问题说明文本失败');
          this.studyInfoText = '第四十八条 军队院校实行学员综合素质考核和全程筛选制度。院校应当对学员的思想政治、科学文化、军事专业、领导管理和身体心理等方面的综合素质进行定期考核，不合格的按照有关规定处理。第四十九条 学员在规定的修业年限内，学完教学计划规定的全部课程或者修满相应的学分，经考核合格的，准予毕业;未达到毕业条件的，作结业或者肄业处理。';
        }
      } catch (error) {
        console.error('加载学习问题说明文本出错:', error);
        this.studyInfoText = '第四十八条 军队院校实行学员综合素质考核和全程筛选制度。院校应当对学员的思想政治、科学文化、军事专业、领导管理和身体心理等方面的综合素质进行定期考核，不合格的按照有关规定处理。第四十九条 学员在规定的修业年限内，学完教学计划规定的全部课程或者修满相应的学分，经考核合格的，准予毕业;未达到毕业条件的，作结业或者肄业处理。';
      }
    },

    // 加载健康问题说明文本
    async loadHealthInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"4、"后面的文本，直到下一个序号或文件结束
          const regex = /4、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.healthInfoText = match[1].trim();
            console.log('健康问题说明文本:', this.healthInfoText);
          } else {
            console.error('未找到健康问题说明文本');
            this.healthInfoText = '第二百一十条  军人患病，应当及时将病情报告直接首长，经批准前往就医，由经治医师决定门诊、住院或者回队治疗，并根据病情开具相关证明。对急症病人，军队医疗卫生机构应当随时诊治。';
          }
        } else {
          console.error('加载健康问题说明文本失败');
          this.healthInfoText = '第二百一十条  军人患病，应当及时将病情报告直接首长，经批准前往就医，由经治医师决定门诊、住院或者回队治疗，并根据病情开具相关证明。对急症病人，军队医疗卫生机构应当随时诊治。';
        }
      } catch (error) {
        console.error('加载健康问题说明文本出错:', error);
        this.healthInfoText = '第二百一十条  军人患病，应当及时将病情报告直接首长，经批准前往就医，由经治医师决定门诊、住院或者回队治疗，并根据病情开具相关证明。对急症病人，军队医疗卫生机构应当随时诊治。';
      }
    },

    // 根据预警原因返回对应的CSS类名
    getWarningReasonClass(warningReason) {
      if (!warningReason) return '';

      // 根据预警原因的内容返回不同的CSS类
      const reason = warningReason.toString().toLowerCase();

      if (reason.includes('学习') || reason.includes('成绩') || reason.includes('考试')) {
        return 'warning-reason-study';
      } else if (reason.includes('健康') || reason.includes('就医') || reason.includes('身体') || reason.includes('医疗')) {
        return 'warning-reason-health';
      } else if (reason.includes('生活') || reason.includes('内务') || reason.includes('纪律')) {
        return 'warning-reason-life';
      } else if (reason.includes('思想') || reason.includes('心理') || reason.includes('政治')) {
        return 'warning-reason-mental';
      } else if (reason.includes('社交') || reason.includes('人际') || reason.includes('交往')) {
        return 'warning-reason-social';
      } else {
        return 'warning-reason-other';
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.key-person-list {
  width: 100%;
  height: 100%;
  padding: 20px;
  color: #d3d6dd;
  background-image: url("~@/assets/pageBg.png");
  background-size: cover;
  background-position: center center;

  .warning-level-1 {
    color: #67c23a; // 绿色 - 低风险
  }

  .warning-level-2 {
    color: #e6a23c; // 黄色 - 中风险
  }

  .warning-level-3 {
    color: #f56c6c; // 红色 - 高风险
  }

  .warning-level-4 {
    color: #ff0000;
    font-weight: bold; // 加粗红色 - 极高风险
  }

  // 预警原因背景颜色样式
  .warning-reason-study {
    background-color: rgba(103, 194, 58, 0.2); // 绿色背景 - 学习问题
    color: #67c23a;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .warning-reason-health {
    background-color: rgba(245, 108, 108, 0.2); // 红色背景 - 健康问题
    color: #f56c6c;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .warning-reason-life {
    background-color: rgba(230, 162, 60, 0.2); // 橙色背景 - 生活问题
    color: #e6a23c;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .warning-reason-mental {
    background-color: rgba(153, 102, 255, 0.2); // 明亮紫色背景 - 思想问题
    color: #9966ff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .warning-reason-social {
    background-color: rgba(64, 158, 255, 0.2); // 蓝色背景 - 社交问题
    color: #409eff;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .warning-reason-other {
    background-color: rgba(104, 216, 254, 0.2); // 青色背景 - 其他问题
    color: #68d8fe;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
  }

  .filter-container {
    margin: 15px 0;
    display: flex;
    align-items: center;

    .filter-label {
      font-size: 14px;
      margin-right: 10px;
      color: #d3d6dd;
    }

    .filter-options {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .filter-option {
        padding: 5px 15px;
        border-radius: 4px;
        background-color: rgba(104, 216, 254, 0.1);
        border: 1px solid rgba(104, 216, 254, 0.3);
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background-color: rgba(104, 216, 254, 0.2);
          transform: translateY(-2px);
        }

        &.active {
          background-color: rgba(104, 216, 254, 0.3);
          border-color: rgba(104, 216, 254, 0.8);
          box-shadow: 0 0 8px rgba(104, 216, 254, 0.4);
        }
      }
    }
  }
  :deep(.el-table) {
    background-color: transparent;
    height: 100%;
    border: 2px solid #68d8fe;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(104, 216, 254, 0.3);

    th {
      background: linear-gradient(to bottom, #2c3e50, #1d2127) !important;
      border-bottom: 2px solid #68d8fe;
      border-right: 1px solid #68d8fe;
      font-weight: bold;
      padding: 15px 0;
      font-size: 16px !important;
      color: #68d8fe !important;
    }

    td {
      background-color: rgba(29, 33, 39, 0.8);
      border-bottom: 1px solid #68d8fe;
      border-right: 1px solid #68d8fe;
      color: #fff;
      padding: 12px 0;
      transition: background-color 0.2s ease;
    }

    .even-row td {
      background-color: rgba(29, 33, 39, 0.8);
    }

    .odd-row td {
      background-color: rgba(19, 25, 47, 0.8);
    }

    .el-table__row:hover > td {
      background-color: rgba(45, 50, 62, 0.9) !important;
    }

    .el-table__header-wrapper {
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
      overflow: hidden;
    }

    .el-table__body-wrapper {
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      overflow-y: auto !important;
      overflow-x: hidden;
      max-height: 100%;
      scrollbar-width: thin;
      scrollbar-color: #68d8fe #1d2127;

      &::-webkit-scrollbar {
        width: 8px;
      }

      &::-webkit-scrollbar-track {
        background: #1d2127;
        border-radius: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #68d8fe;
        border-radius: 4px;
        border: 2px solid #1d2127;
      }
    }

    // Remove last column's right border
    th:last-child,
    td:last-child {
      border-right: none;
    }

    // Fix border issues
    &::before {
      display: none;
    }

    .el-table__fixed::before,
    .el-table__fixed-right::before {
      display: none;
    }
  }

  .module-container {
    height: 100%;
    display: flex;
    flex-direction: column;

    .module-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .header-icon {
        font-size: 24px;
        color: #68d8fe;
        margin-right: 10px;
      }

      .header-title {
        font-size: 22px;
        font-weight: bold;
        color: #68d8fe;
      }
    }

    .category-tabs {
      display: flex;
      margin-bottom: 20px;
      background-color: rgba(19, 25, 47, 0.6);
      border-radius: 6px;
      padding: 5px;
      overflow-x: auto;

      .tab-item {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px 15px;
        margin: 0 5px;
        border-radius: 4px;
        cursor: pointer;
        white-space: nowrap;
        transition: all 0.3s ease;

        &:hover {
          background-color: rgba(104, 216, 254, 0.1);
        }

        &.active {
          background-color: rgba(104, 216, 254, 0.2);
          border-bottom: 2px solid #68d8fe;
        }

        .tab-icon {
          font-size: 16px;
          color: #68d8fe;
          margin-right: 8px;
        }

        .tab-text {
          font-size: 14px;
          color: #d3d6dd;
        }
      }
    }

    .module-content {
      flex: 1;

      .content-box {
        height: 100%;
        padding: 20px;
      }

      .tab-content {
        height: 100%;
        display: flex;
        flex-direction: column;
      }

      .sub-tab-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: calc(100% - 40px);
        position: relative;
        overflow: hidden;
      }

      .health-title {
        font-size: 16px;
        color: #68d8fe;
        margin-bottom: 15px;
        padding-left: 10px;
        border-left: 3px solid #68d8fe;
      }

      .loading-indicator {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100px;
        color: #68d8fe;
        font-size: 16px;
      }

      .no-data-message {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 30px;
        color: #8a8a8a;

        p {
          margin-bottom: 15px;
          font-style: italic;
        }

        .reload-btn {
          padding: 8px 15px;
          background-color: rgba(104, 216, 254, 0.2);
          border: 1px solid #68d8fe;
          color: #68d8fe;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s ease;

          &:hover {
            background-color: rgba(104, 216, 254, 0.3);
          }
        }
      }

      .data-summary {
        margin-top: 15px;
        text-align: right;
        font-size: 14px;
        color: #d3d6dd;

        .highlight {
          color: #ff6b6b;
          font-weight: bold;
          font-size: 16px;
        }
      }

      .health-table-container {
        width: 100%;
        overflow-x: auto;
        margin-bottom: 20px;

        .health-table {
          width: 100%;
          border-collapse: collapse;
          border: 1px solid rgba(104, 216, 254, 0.3);
        }
      }

      .study-table-container {
        width: 100%;
        overflow-y: auto;
        margin-bottom: 0;
        max-height: 100%;

        .table-responsive {
          width: 100%;
          height: 100%;
          overflow-y: auto;

          &::-webkit-scrollbar {
            width: 6px;
          }

          &::-webkit-scrollbar-track {
            background: rgba(19, 25, 47, 0.5);
            border-radius: 3px;
          }

          &::-webkit-scrollbar-thumb {
            background-color: rgba(104, 216, 254, 0.5);
            border-radius: 3px;
          }
        }

        .study-table {
          width: 100%;
          border-collapse: collapse;
          border: 1px solid rgba(104, 216, 254, 0.3);

          th,
          td {
            padding: 10px;
            text-align: center;
            border: 1px solid rgba(104, 216, 254, 0.3);
          }

          th {
            background-color: rgba(104, 216, 254, 0.1);
            color: #68d8fe;
            font-weight: bold;
          }

          tr:nth-child(even) {
            background-color: rgba(19, 25, 47, 0.4);
          }

          tr:hover {
            background-color: rgba(104, 216, 254, 0.1);
          }

          .highlight {
            color: #ff6b6b;
            font-weight: bold;
          }

          .failed {
            color: #ff6b6b;
          }

          .student-name {
            color: #68d8fe;
            cursor: pointer;
            text-decoration: underline;

            &:hover {
              color: #9be3ff;
            }
          }

          .no-data {
            padding: 20px;
            color: #8a8a8a;
            font-style: italic;
          }
        }
      }

      .study-problem-container {
        height: 100%;
        display: flex;
        flex-direction: column;

        .study-title {
          font-size: 16px;
          color: #68d8fe;
          margin-bottom: 15px;
          padding-left: 10px;
          border-left: 3px solid #68d8fe;
          flex-shrink: 0;
          position: relative;

          .title-text-container {
            display: flex;
            align-items: center;
            gap: 8px;

            .title-icon-container {
              position: relative;
              display: flex;
              align-items: center;

              .book-icon {
                font-size: 18px;
                color: #68d8fe;
                cursor: pointer;
                transition: all 0.3s ease;

                &:hover {
                  color: #9be3ff;
                  transform: scale(1.1);
                }
              }

              .mental-tooltip {
                position: absolute;
                top: 30px;
                left: 50%;
                transform: translateX(-50%);
                background-color: rgba(0, 0, 0, 0.85);
                color: #fff;
                padding: 16px 20px;
                border-radius: 8px;
                font-size: 20px;
                line-height: 1.6;
                width: 320px;
                height: 280px;
                white-space: pre-wrap;
                word-wrap: break-word;
                z-index: 1000;
                border: 1px solid #68d8fe;
                box-shadow: 0 6px 20px rgba(104, 216, 254, 0.4);
                animation: fadeIn 0.3s ease;
                overflow-y: auto;
                display: flex;
                align-items: center;
                justify-content: center;
                text-align: center;
              }

              .study-tooltip {
                position: absolute;
                top: 30px;
                left: 80px;
                background-color: rgba(0, 0, 0, 0.85);
                color: #fff;
                padding: 20px 25px;
                border-radius: 8px;
                font-size: 18px;
                line-height: 1.8;
                width: 480px;
                height: 360px;
                white-space: pre-wrap;
                word-wrap: break-word;
                z-index: 1000;
                border: 1px solid #68d8fe;
                box-shadow: 0 6px 20px rgba(104, 216, 254, 0.4);
                animation: fadeIn 0.3s ease;
                overflow-y: auto;
                display: flex;
                align-items: flex-start;
                justify-content: flex-start;
                text-align: justify;
                text-indent: 2em;
              }

              .health-tooltip {
                position: absolute;
                top: 30px;
                left: 80px;
                background-color: rgba(0, 0, 0, 0.85);
                color: #fff;
                padding: 20px 25px;
                border-radius: 8px;
                font-size: 18px;
                line-height: 1.8;
                width: 480px;
                height: 280px;
                white-space: pre-wrap;
                word-wrap: break-word;
                z-index: 1000;
                border: 1px solid #68d8fe;
                box-shadow: 0 6px 20px rgba(104, 216, 254, 0.4);
                animation: fadeIn 0.3s ease;
                overflow-y: auto;
                display: flex;
                align-items: flex-start;
                justify-content: flex-start;
                text-align: justify;
                text-indent: 2em;
              }

              @keyframes fadeIn {
                from {
                  opacity: 0;
                  transform: translateX(-50%) translateY(-10px);
                }
                to {
                  opacity: 1;
                  transform: translateX(-50%) translateY(0);
                }
              }
            }
          }
        }

        .study-table-wrapper {
          flex: 1;
          display: flex;
          flex-direction: column;
          height: calc(100% - 40px);
          overflow: hidden;
          position: relative;
          min-height: 300px;
        }

        .study-table-container {
          flex: 1;
          overflow-y: auto;
          padding-right: 5px;
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;

          &::-webkit-scrollbar {
            width: 6px;
          }

          &::-webkit-scrollbar-track {
            background: rgba(19, 25, 47, 0.5);
            border-radius: 3px;
          }

          &::-webkit-scrollbar-thumb {
            background-color: rgba(104, 216, 254, 0.5);
            border-radius: 3px;
          }
        }
      }

      .placeholder-content {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: rgba(19, 25, 47, 0.6);

        .text-center {
          text-align: center;

          .title {
            font-size: 24px;
            color: #68d8fe;
            margin-bottom: 15px;
          }

          .description {
            font-size: 16px;
            color: #d3d6dd;
          }
        }
      }
    }
  }
}
</style>
